<?php
/**
 * 用户
 * Created by PhpStorm.
 * User: andy
 * Date: 2019/8/29
 * Time: 下午6:42
 */

namespace app\common\model;

use think\Model;

class MemberModel extends Model
{
    const STATUS_SHOW = 1; //显示
    const STATUS_HIDE = 0; //禁用
    const STATUS_DEL = -1; //删除

    protected $autoWriteTimestamp = true;

    protected $pk = "uid";

    public static function init()
    {
        self::afterInsert(function ($user) {
            $user->invite_code = createInviteCode($user->uid);
            $user->save();
        });
    }

    /**
     * 所有用户
     * @param int $pageSum
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getALL($where = [], $pageSum = 0)
    {
        if ($pageSum <= 0) {
            $pageSum = getSystem("pageSUM") ? getSystem("pageSUM") : 10;
        }

        //$list = self::where($where)->order("real_name_status asc,code_front desc")->paginate($pageSum);
        $list = self::where($where)->order("create_time desc")->paginate($pageSum);

        return $list;
    }

    /**
     * 获取导出数据
     * @param array $where
     * @return array|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getSelect($where = [])
    {
        $list = self::where('status', '>', self::STATUS_DEL)
            ->where($where)
            ->select();

        return $list;
    }

    /**
     * 增加分组
     * @param $data
     * @return bool
     */
    public function addUser($data)
    {
        //检测当前应用方法名是否重复
        if (!self::chackAction($data)) {
            return ['status' => 0, 'msg' => '用户已存在！'];
        }

        if (empty($data['uid'])) {
            $salt = random_string();;
            $data["salt"] = $salt;
            $data["mobile_validated"] = 1;
            $data["oauth"] = $data["oauth"] ? $data["oauth"] : "后台注册";
            $data["nickname"] = $data["mobile"];

            if (isset($data["password"])) $data["password"] = password($data["password"], $salt);

            $status = self::save($data);

            if ($status) {
                return ['status' => 1, 'msg' => '增加成功！'];
            } else {
                return ['status' => 0, 'msg' => '增加失败！'];
            }
        } else {
            $info = self::field("salt")->get($data["uid"]);

            if (!empty($data["password"])) {
                $data["password"] = password($data["password"], $info["salt"]);
            }


            $status = self::save($data, ['uid' => $data["uid"]]);

            if ($status) {
                return ['status' => 1, 'msg' => '修改成功！'];
            } else {
                return ['status' => 0, 'msg' => '修改失败！'];
            }
        }

    }

    /**
     * 修改密码
     * @param $data
     * @return array
     * @throws \think\Exception\DbException
     */
    public function updatePwd($data)
    {
        $info = self::field("uid")->where("mobile", "=", $data["mobile"])->find();

        if (!empty($data["password"])) {
            $data["password"] = password($data["password"], $info["salt"]);
        }


        $status = self::save($data, ['uid' => $info["uid"]]);

        if ($status) {
            return ['status' => 1, 'msg' => '修改成功！'];
        } else {
            return ['status' => 0, 'msg' => '修改失败！'];
        }
    }

    /**
     * 删除
     * @param $id
     * @return array
     */
    public function del($id)
    {

        $au = self::get($id);
        $au->status = self::STATUS_DEL;

        $status = $au->save();
        if ($status) {
            return ['status' => 1, 'msg' => '删除成功！'];
        } else {
            return ['status' => 0, 'msg' => '删除失败！'];
        }

    }

    /**
     * 检测当前是否重复
     * @param $data
     * @return bool
     */
    private static function chackAction($data)
    {
        if (empty($data['uid'])) {
            $data['uid'] = 0;
        }

        $count = self::where('mobile', $data['mobile'])
            ->where('uid', "<>", $data['uid'])
            ->where('status', "<>", self::STATUS_DEL)
            ->count();

        if ($count > 0) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 检测后台登陆
     * @param $username
     * @param $pwd
     * @return array|null|\PDOStatement|string|Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function check_login($username, $pwd)
    {
        $info = self::where('username', $username)->find();

        if (empty($info)) {
            return ['status' => 0, 'msg' => '管理员不存在！'];
        }

        if ($info['status'] != self::STATUS_SHOW) {
            return ['status' => 0, 'msg' => '管理员已禁用！'];
        }

        if (password($pwd, $info['salt']) != $info['password']) {
            return ['status' => 0, 'msg' => '密码错误！'];
        }

        return ['status' => 1, 'data' => $info];
    }

    /**
     * 获得佣金
     * @param $user_id
     * @param $type 类型：0 汽车，1 汽车评论，2 文章评论
     * @param $id
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public static function pushGold($user_id, $type,$id)
    {
        if ($user_id <= 0) return true;

        $user = self::get($user_id);

        if (!$user) return false;

        $carMoney = getSystem("get_money") ? getSystem("get_money") : 0;

        $giveMoney = getSystem("getMsgMoney") ? getSystem("getMsgMoney") : 0;
        $msgMax = getSystem("msgMax") ? getSystem("msgMax") : 0;



        self::startTrans();
        try {
            if($type==0){
                $uc=UserCarModel::find($id);

                if(!$uc){
                    self::commit();
                    return true;
                }
                if($uc['lock_gold']){
                    self::commit();
                    return true;
                }

                if($carMoney<=0){
                    self::commit();
                    return true;
                }

                //发布车辆获得
                $status = self::where('uid', $user_id)->setInc("distribut_money", $carMoney);
                if ($status) {
                    $uc->gold=1;
                    $uc->lock_gold=1;
                    $uc->gold_money=$carMoney;
                    $uc->save();
                    UserRecordModel::adds($user_id, UserRecordModel::SHOW_STATUS, $carMoney, $user->distribut_money, "发布车辆获得{$carMoney}元",'发布车辆');
                }
            }else if($type==1 || $type==2){
                //汽车评论获得
                //判断今日是否超限
                $today=strtotime(date('Y-m-d 00:00:00'));

                if($giveMoney<=0){
                    self::commit();
                    return true;
                }

                if($type==1){
                    $count=UserCarMessageModel::where('create_time','>=',$today)
                        ->where('user_id',$user_id)
                        ->count();
                    $msg="发布汽车留言评论获得{$giveMoney}元";
                    $title="汽车评论";

                    $msgAction=UserCarMessageModel::find($id);
                }else{
                    $count=ArticleMessageModel::where('create_time','>=',$today)
                        ->where('user_id',$user_id)
                        ->count();
                    $msg="发布文章留言评论获得{$giveMoney}元";
                    $title="文章评论";

                    $msgAction=ArticleMessageModel::find($id);
                }

                if(!$msgAction) return true;
                if($msgAction['lock_gold']) return true;

                if($count>=$msgMax){
                    $msgAction->gold=1;
                    $msgAction->back_gold=1;
                    $msgAction->lock_gold=1;
                    $msgAction->save();

                    self::commit();
                    return true;
                }

                $status = self::where('uid', $user_id)->setInc("distribut_money", $giveMoney);
                if ($status) {
                    $msgAction->gold=1;
                    $msgAction->lock_gold=1;
                    $msgAction->gold_money=$giveMoney;
                    $msgAction->save();
                    UserRecordModel::adds($user_id, UserRecordModel::SHOW_STATUS, $giveMoney, $user->distribut_money, $msg,$title);
                }
            }
            self::commit();
        } catch (\Exception $e) {
            self::rollback();
        }
    }

    /**
     * 退回佣金
     * @param $id
     * @param $type  类型：0 汽车，1 汽车评论，2 文章评论
     * @return bool
     * @throws \think\Exception
     */
    public static function subGold($id,$type){
        $msg="";
        switch ($type){
            case 0:
                $mode=UserCarModel::find($id);
                $msg="发布车辆未通过，扣除佣金";
                $title="发布车辆";
                break;
            case 1:
                $mode=UserCarMessageModel::find($id);
                $msg="发布留言未通过，扣除佣金";
                $title="车辆评论";
                break;
            case 2:
                $mode=ArticleMessageModel::find($id);
                $msg="发布留言未通过，扣除佣金";
                $title="文章评论";
                break;
        }

        if(empty($mode)) return true;
        if($mode['back_gold']) return true;

        $user=self::find($mode['user_id']);

        if(empty($user)) return true;

        $giveMoney=$mode['gold_money'];

        if($giveMoney<=0) return true;

        self::startTrans();

        $status = self::where('uid', $user['uid'])->setDec("distribut_money", $giveMoney);
        if ($status) {
            $mode->back_gold=1;
            $mode->save();
            UserRecordModel::adds($user['uid'], UserRecordModel::Z_STATUS, $giveMoney, $user->distribut_money, $msg,$title);
            self::commit();
        }
        self::rollback();
    }

}